import { RootState } from './../index';
import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";

export type Counter ={
    count: number;
    randomNumber?: number;
}

const initialState: Counter = {
    count: 0
};

const counterSlicer = createSlice({
    name: "counter", 
    initialState,
    reducers: {
        // Redux Toolkit allows us to write "mutating" logic in reducers. It
        // doesn't actually mutate the state because it uses the Immer library,
        // which detects changes to a "draft state" and produces a brand new
        // immutable state based off those changes
        increment(state, action: PayloadAction<number>) {
            console.log(action);
            if (!action) {
                state.count++;
                return;
            }
               
            state.count += action.payload;
        },
        decrement(state, action: PayloadAction<number>) {
            if (!action) {
                state.count--;
                return;
            }
               
            state.count -= action.payload;
        },
        setNumber(state, action: PayloadAction<number>){
            state.randomNumber = action.payload;
        }
    }
});

// export actions
export const { increment, decrement, setNumber } = counterSlicer.actions;

export const selectCounter = (state: RootState) => state.counter;

export default counterSlicer.reducer;